#!/usr/bin/env bash

##根据ip获取C段地址数字
function ip2ClassNum()
{
    ip=$1
    a=`echo $ip | awk -F'.' '{print $1}'`
    b=`echo $ip | awk -F'.' '{print $2}'`
    c=`echo $ip | awk -F'.' '{print $3}'`
    d=`echo $ip | awk -F'.' '{print $4}'`
 
    echo "$(((a<<16)+(b<<8)+c))"
}

##C段ip地址数字转换为ip地址
function cClassNum2Ip()
{
    num=$(($1<<8))
    a=$((num>>24))
    b=$((num>>16&0xff))
    c=$((num>>8&0xff))
    d=$((num&0xff))
 
    echo "$a.$b.$c.$d"
}

##从思科地址表示法中获取ip
function splitIp()
{
	str=$1
	echo $str | awk -F'/' '{print $1}'
}

##从思科地址表示法中获取子网掩码位数
function splitMask()
{
	str=$1
	echo $str | awk -F'/' '{print $2}'
}

##根据子网掩码位数转换为子网掩码字符串
function makeMaskStr()
{
	x=""
	num=$1
	for i in {1..24}
	do
		if [ $i -le $num ]
		then 
			x=${x}"1"
		else
			x=${x}"0"
		fi
	done
	echo $x 
}


export -f ip2ClassNum
export -f splitIp
export -f splitMask

echo "开始拉取远程地址库..."
today=`date +%Y%m%d`
curl 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | grep ipv4 | grep CN | awk -F\| '{ printf("%s/%d\n", $4, 32-log($5)/log(2)) }' > $today.txt

todayFileMD5=`md5sum $today.txt|cut -d ' ' -f1`
preFileMD5=`md5sum china_ip.txt|cut -d ' ' -f1`

if [ $todayFileMD5"x" = $preFileMD5"x" ] 
then
	rm $today.txt
	echo "地址库未发生变化，跳过更新"
	exit
else
	mv $today.txt china_ip.txt
fi

echo "开始解析..."
rm ipNew.txt
for x in ` awk '{print $1}' china_ip.txt `  
{  
	ip=`splitIp $x`
	echo "ip: "$ip
	mask=`splitMask $x`
	echo "mask:"$mask
	n=$((24-$mask))
	total=$((2**$n))
	echo "共："$total
	ipNum=`ip2ClassNum $ip`
	i=0
	while(( $i<=$total ))
	do 
		newIpNum=$(($ipNum+$i))  
		# echo $newIpNum              
		echo "find:"`cClassNum2Ip $newIpNum`
		printf '{"ip":%s,"country":39}\n' $newIpNum >> ipNew.txt
		let "i++"
	done 
}
mv ipNew.txt ip.txt
echo "完成"